package at.xtools.pwawrapper.ui;

import at.xtools.pwawrapper.Constants;
import at.xtools.pwawrapper.ResourceTable;
import ohos.aafwk.ability.Ability;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.webengine.WebView;

public class UIManager {
    // Instance variables
    private Ability activity;
    private WebView webView;
    private ProgressBar progressSpinner;
    private ProgressBar progressBar;
    private DependentLayout offlineContainer;
    private boolean pageLoaded = false;

    public UIManager(Ability activity) {
        this.activity = activity;
        this.progressBar = (ProgressBar) activity.findComponentById(ResourceTable.Id_progressBarBottom);
        this.progressSpinner = (ProgressBar) activity.findComponentById(ResourceTable.Id_progressSpinner);
        this.offlineContainer = (DependentLayout) activity.findComponentById(ResourceTable.Id_offlineContainer);
        this.webView = (WebView) activity.findComponentById(ResourceTable.Id_webView);
        // set click listener for offline-screen
        offlineContainer.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                webView.load(Constants.WEBAPP_URL);
                setOffline(false);
            }
        });
    }

    // Set Loading Progress for ProgressBar
    public void setLoadingProgress(int progress) {
        // set progress in UI
        progressBar.setProgressValue(progress);

        // hide ProgressBar if not applicable
        if (progress >= 0 && progress < 100) {
            progressBar.setVisibility(Component.VISIBLE);
        } else {
            progressBar.setVisibility(Component.INVISIBLE);
        }

        // get app screen back if loading is almost complete
        if (progress >= Constants.PROGRESS_THRESHOLD && !pageLoaded) {
            setLoading(false);
        }
    }

    // Show loading animation screen while app is loading/caching the first time
    public void setLoading(boolean isLoading) {
        if (isLoading) {
            progressSpinner.setVisibility(Component.VISIBLE);
        } else {
            progressSpinner.setVisibility(Component.INVISIBLE);
        }
        pageLoaded = !isLoading;
    }

    // handle visibility of offline screen
    public void setOffline(boolean offline) {
        if (offline) {
            setLoadingProgress(100);
            webView.setVisibility(Component.INVISIBLE);
            offlineContainer.setVisibility(Component.VISIBLE);
        } else {
            webView.setVisibility(Component.VISIBLE);
            offlineContainer.setVisibility(Component.INVISIBLE);
        }
    }

    // set icon in recent activity view to a white one to be visible in the app bar
    public void changeRecentAppsIcon() {
    }
}
